package com.example.fw;

import static org.hamcrest.Matchers.*;
import static org.hamcrest.MatcherAssert.assertThat;
import java.awt.Container;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JLabel;
import org.netbeans.jemmy.operators.JButtonOperator;
import org.netbeans.jemmy.operators.JDialogOperator;
import org.netbeans.jemmy.operators.JLabelOperator;
import org.netbeans.jemmy.operators.JTextFieldOperator;
import org.netbeans.jemmy.operators.JTreeOperator;
import org.testng.Assert;

public class FolderHelper extends HelperBase{
	
	public FolderHelper(ApplicationManager applicationManager) {
		super(applicationManager);
	}

	public Folders getFolders() {
		
		List<String> list = new ArrayList<>();
		JTreeOperator tree = new JTreeOperator(mainFrame);
		Object[] children = tree.getChildren(tree.getRoot());
		for (Object child : children){
			list.add("" + child);
		}
		return new Folders(list);
	}
	
	private int getFolderIndex(Object[] children, String folder){
		
		for (int i = 0; i < children.length; i++){
			if (children[i].toString().equals(folder)){
				return i;
			}	
		}
		Assert.fail("Folder [" + folder + "] not found");
		return -1;
	}

	public String createFolder(String folderName) {
		
		manager.getMenuHelper().pushCreateFolder();
		JDialogOperator dialog = new JDialogOperator(mainFrame,"Enter");
		new JTextFieldOperator(dialog).setText(folderName);
		new JButtonOperator(dialog, "OK").push();
		return waitMessageDialog("Warning", 3000);
	}

	public String deleteFolder(String folder) {
		
		JTreeOperator tree = new JTreeOperator(mainFrame);
		int index = getFolderIndex(tree.getChildren(tree.getRoot()),folder);
		tree.setSelectionRow(index);
		tree.requestFocus();
		
		manager.getMenuHelper().pushDeleteFolder();	
		JDialogOperator dialog = new JDialogOperator(mainFrame,"AddressBook: Confirm");
		
		String textLabel = "Are you sure to delete folder?";
		Container contents = dialog.getContentPane();
		JLabel confirmationLabel = JLabelOperator.findJLabel(contents, textLabel, false, false);
		//Assert.assertNotNull(confirmationLabel, "Invalid confirmation message");
		assertThat(confirmationLabel, notNullValue());
		
		new JButtonOperator(dialog, "YES").push();
		return waitMessageDialog("Warning", 3000); 	
	}
	
}
